package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    VehicleMapper vehicleMapper;
    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery vehicleQuery) {
        log.debug("查询车辆业务:vehicleQuery={}",vehicleQuery);
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        return list;
    }

    @Override
    public void saveVehicle(VehicleSaveParam vehicleSaveParam) {
        log.debug("保存车辆业务:vehicleSaveParam={}",vehicleSaveParam);
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleSaveParam,vehicle);
        //判断要进行插入还是更新操作
        if(vehicle.getId()==null){//新增
            vehicle.setCreateTime(new Date());
            vehicle.setStatus("1");//空闲
            vehicleMapper.insert(vehicle);
        }else{//更新
            vehicle.setUpdateTime(new Date());
            vehicleMapper.update(vehicle);
        }
    }

    @Override
    public void deleteVehicle(Long id) {
        log.debug("删除车辆业务:id={}",id);
        vehicleMapper.deleteVehicle(id);
    }

    @Override
    public void unbindVehicle(Long vehicleId) {
        log.debug("解绑车辆业务:vehicleId={}",vehicleId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);//设置车辆id,也就是改哪辆车的数据
        vehicle.setGeofenceBindStatus("0");//围栏绑定状态,注意是String类型
        vehicle.setUpdateTime(new Date());//车辆的更新时间
        vehicle.setGeofenceId(null);//车辆绑定的围栏id置为null
        /*之前的更新SQL要求围栏编号不能为null才会更新围栏编号
        * 但此处由于业务=>将车辆与围栏解除绑定关系
        * 需要将围栏编号置为null,所以需要重写一个mapper层的方法*/
        vehicleMapper.updateNullValue(vehicle);
    }

    @Override
    public void bindVehicle(Long geofenceId, Long vehicleId) {
        log.debug("绑定车辆业务:geofenceId={},vehicleId={}",geofenceId,vehicleId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setGeofenceId(geofenceId);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}
